package com.yc.yuapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yc.yuapiclientsdk.model.User;
import com.yc.yuapiclientsdk.model.Word;
import com.yc.yuapiclientsdk.utils.SignUtils;


import java.util.HashMap;
import java.util.Map;

/**
 * 调用第三方接口的客户端
 *
 * @author WangJiYou
 **/
public class YuApiClient {
    public static final  String GATEWAY_HOST="http://localhost:8090";

    private String accessKey;
    private String secretKey;

    public YuApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get("http://localhost:8123/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post("http://localhost:8123/api/name/", paramMap);
        System.out.println(result);
        return result;
    }


    public String getUsernameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST+"/api/name/user/post")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }

//    public String getChineseByPost(Word word) {
//        String json = JSONUtil.toJsonStr(word);
//        Map<String, String> headerMap = new HashMap<>();
//        headerMap.put("User-Agent", "Mozilla/......");
//        HttpResponse httpResponse = HttpRequest.post("https://fanyi.baidu.com/sug")
//                .addHeaders(headerMap)
//                .body(json)
//                .execute();
//        System.out.println(httpResponse.getStatus());
//        String result = httpResponse.body();
//        System.out.println(result);
//        return result;
//    }

    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hasMap = new HashMap<>();
        hasMap.put("accessKey", accessKey);
        hasMap.put("nonce", RandomUtil.randomNumbers(4));
        hasMap.put("body", body);
        hasMap.put("timeTamp", java.lang.String.valueOf(System.currentTimeMillis()));
        hasMap.put("sign", SignUtils.getSign(body, secretKey));
        return hasMap;
    }


}
